// DB
var _DB_ = window.indexedDB.open("catalog");
//_DB_.dtd = $.Deferred();
_DB_.onsuccess = initTable;
_DB_.onupgradeneeded = createTable;
_DB_.onerror = function (event) {
    console.log('数据库打开报错:' + event);
};

var DB = {
    handle : null,
    createTable : function (table, key) {
        if (!DB.handle.objectStoreNames.contains(table)) {
            DB.handle.createObjectStore(table, { keyPath: key });
        }
    },
    getTable : function (table) {
        var dtd = new Promise(function (resolve, reject) {
            var request = DB.handle.transaction(table).objectStore(table).openCursor();
            var data = [];
            request.onsuccess = function (event) {
                var cursor = event.target.result;
                if (cursor) {
                    data.push(cursor.value);
                    cursor.continue();
                } else {
                    resolve(data);
                }
            };
            request.onerror = function (event) {
                reject();
            };
        });
        return dtd;
    },
    getTableRow : function (table, key) {
        var dtd = new Promise(function (resolve, reject) {
            try {
                var request = DB.handle.transaction(table).objectStore(table).get(key);
                request.onsuccess = function (event) {
                    if (request.result) {
                        resolve(request.result);
                    } else {
                        reject();
                    }
                };
                request.onerror = function (event) {
                    reject();
                };
            } catch (e) {
                reject();
            }
        });
        return dtd;
    },
    setTableRow : function (table, row) {
        var dtd = new Promise(function (resolve, reject) {
            var request = DB.handle.transaction(table, 'readwrite')
                .objectStore(table)
                .put(row);

            request.onsuccess = function (event) {
                resolve(event);
            };

            request.onerror = function (event) {
                reject();
            };
        });
        return dtd;
    },
    deleteTableRow : function (table, key) {
        var dtd = new Promise(function (resolve, reject) {
            var request = DB.handle.transaction(table, 'readwrite')
                .objectStore(table)
                .delete(key);

            request.onsuccess = function (event) {
                resolve(event);
            };

            request.onerror = function (event) {
                reject();
            };
        });
        return dtd;
    },
};

function initTable(event) {
    DB.handle = event.target.result;
    try {
        createTable(event);
    } catch (e) {

    }
}

function createTable(event) {
    DB.createTable("user", "id");
    DB.createTable("stock", "id");
    DB.createTable("source", "index");
    DB.createTable("select", "id");
}